var locationData = require('../../../staticData/locationKeyValue.json');
exports.customersWhoBuyProductsToday = (req, res) => {

    var restfulParams = req.routeInfo.restfulParams;

    var resultData = {};

    var todayStart = new Date(new Date().toLocaleDateString()).getTime() / 1000;

    var todayEnd = (new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000) / 1000;

    var customerTodayOrdersInfo = 0;

    var viewCustomers = [];

    var u_id = restfulParams.u_id;

    var is_manager = restfulParams.is_manager;//是否是管理 0-否 1-是

    var apo_invite_code_condition = '';

    var u_type = restfulParams.u_type;

    var u_osid = restfulParams.os_id;

    var salesArr = [];

    var userInStr = '';

    //查询员工
    function salesSearch(cb) {
        if (is_manager == 1 && (u_type == 1 || u_type == 2)) {

            //战略  查询战略伙伴下所有销售
            console.log("战略 || 代理");
            R.SEND_HTTP(
                req,
                res, {
                    url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_master_osid/" + u_osid,
                    method: 'POST',
                    data: {
                        fields: ['u_id'].join(",")
                    }
                },
                function (data) {

                    salesArr = data.result.data;

                    cb();

                }
            )
        } else if (is_manager == 1 && u_type == 3) {
            //销售主管  查询该销售主管下所有销售.包括自己。
            console.log("销售组长");
            R.SEND_HTTP(
                req,
                res, {
                    url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url + "/u_leader/" + restfulParams.u_id,
                    method: 'POST',
                    data: {
                        fields: ['u_id'].join(",")
                    }
                },
                function (data) {

                    salesArr = data.result.data;

                    cb();

                }
            )
        } else if (is_manager == 0 && u_type == 3) {
            //普通销售
            console.log("普通销售");
            salesArr.push({
                u_id: u_id
            });
            cb();
        } else if (u_type == 0) {
            //超管
            console.log("超管");
            R.SEND_HTTP(
                req,
                res, {
                    url: CORE_APIConfig.coreAPI.userSearch.Request_Api_Url,
                    method: 'POST',
                    data: {
                        fields: ['u_id'].join(",")
                    }
                },
                function (data) {

                    salesArr = data.result.data;
                    cb();

                }
            )
        }
    }

    // 拼接in语句查询条件
    function fixInCondition(cb) {
        console.log(salesArr);
        for (var i = 0; i < salesArr.length; i++) {
            userInStr += salesArr[i].u_id + ","
        }
        userInStr = userInStr.substring(0, userInStr.length - 1);

        if (userInStr == '') {
            userInStr = "null";
        }

        apo_invite_code_condition = "/in/apo_invite_code-" + userInStr;


        cb()
    }

    //查询今日订单
    function customerTodayOrders(cb) {

        var url = config.external_server.apiAddress + "/organization/search_art_product_order" + apo_invite_code_condition + "/apo_status/1";

        R.SEND_HTTP(
            req,
            res,
            {
                url: url,
                method: 'POST',
                data: {
                    fields: ['apo_id', 'apo_openid', 'apo_create_time'].join(",")
                }
            },
            function (data) {
                console.log(data);
                var newOrderArr = [];
                var orderInfo = data.result.data;
                for (var i = 0; i < orderInfo.length; i++) {
                    if (orderInfo[i].apo_create_time > todayStart && orderInfo[i].apo_create_time < todayEnd) {
                        newOrderArr.push(orderInfo[i])
                    }
                }
                customerTodayOrdersInfo = newOrderArr;

                cb();

            }
        )
    }

    //查询客户信息
    function queryForCustomerInfo(cb) {

        F.ParallelEach(customerTodayOrdersInfo, function (item, index, callback) {

            //查询客户信息
            function customerInfo(eachCb) {

                R.SEND_HTTP(
                    req,
                    res,
                    {
                        url: CORE_APIConfig.coreAPI.artCustomerSearch.Request_Api_Url + "/c_is_delete/0/c_openid/" + item.apo_openid,
                        method: 'POST',
                        data: {
                            fields: ['c_id', 'c_name', 'c_header_url', 'c_phone', 'c_campus_name', 'c_provinces', 'c_city', 'c_area', 'c_address', 'c_distribution_status', 'c_follow_status', 'c_evaluation', 'c_service_status', 'c_is_buy'].join(",")
                        }
                    },
                    function (data) {
                        item.customerInfo = data.result.data;
                        if (data.result.data.length > 0) {
                            var provinceId = data.result.data[0].c_provinces;
                            var cityId = data.result.data[0].c_city;
                            var areaId = data.result.data[0].c_area;
                        }
                        if (data.result.data.length > 0) {
                            item.customerInfo[0].provinceName = locationData[provinceId];
                            item.customerInfo[0].cityName = locationData[cityId];
                            item.customerInfo[0].areaName = locationData[areaId];
                        }
                        eachCb();

                    }
                )
            }

            function queryForEachFollowRecord(eachCb) {

                F.ParallelEach(resultData.customerInfo, function (item, index, callback2) {
                    //查询客户跟进信息
                    function followRecordUser(eachCb1) {

                        R.SEND_HTTP(
                            req,
                            res,
                            {
                                url: CORE_APIConfig.coreAPI.vFollowRecordUserSearch.Request_Api_Url + "/count/1/cfr_cid/" + item.c_id + "/sort_order/cfr_id-desc",
                                method: 'POST',
                                data: {
                                    fields: ['cfr_way', 'cfr_create_time', 'u_nickname'].join(',')
                                }
                            },
                            function (data) {

                                if (data.result.data.length > 0) {
                                    item.followInfo = data.result.data[0];
                                } else {
                                    item.followInfo = [];
                                }

                                item.followCount = data.result.count;

                                eachCb1();

                            }
                        )
                    }

                    F.Parallel([
                        followRecordUser,
                    ], () => {
                        callback2();
                    })
                }, eachCb)
            }


            F.Parallel([
                customerInfo,
            ], () => {
                callback();
            })

        }, cb)

    }

    //查询客户信息
    function queryForCustomerInfoLoopAgain(cb) {

        F.ParallelEach(customerTodayOrdersInfo, function (item, index, callback) {

            function queryForEachFollowRecord(eachCb) {

                F.ParallelEach(item.customerInfo, function (item2, index, callback2) {
                    //查询客户跟进信息
                    function followRecordUser(eachCb1) {

                        R.SEND_HTTP(
                            req,
                            res,
                            {
                                url: CORE_APIConfig.coreAPI.vFollowRecordUserSearch.Request_Api_Url + "/count/1/cfr_cid/" + item2.c_id + "/sort_order/cfr_id-desc",
                                method: 'POST',
                                data: {
                                    fields: ['cfr_way', 'cfr_create_time', 'u_nickname'].join(',')
                                }
                            },
                            function (data) {

                                if (data.result.data.length > 0) {
                                    item.followInfo = data.result.data[0];
                                } else {
                                    item.followInfo = [];
                                }

                                item.followCount = data.result.count;

                                eachCb1();

                            }
                        )
                    }

                    F.Parallel([
                        followRecordUser,
                    ], () => {
                        callback2();
                    })
                }, eachCb)
            }


            F.Parallel([
                queryForEachFollowRecord,
            ], () => {
                callback();
            })

        }, cb)

    }

    //筛选客户
    function screeningCustomers(cb) {
        for (var i = 0; i < customerTodayOrdersInfo.length; i++) {
            if (customerTodayOrdersInfo[i].customerInfo.length > 0) {
                viewCustomers.push(customerTodayOrdersInfo[i])
            }
        }
        resultData.customerTodayOrders = viewCustomers;
        cb()
    }

    F.Serial([
        salesSearch,
        fixInCondition,
        customerTodayOrders,
        queryForCustomerInfo,
        screeningCustomers,
        queryForCustomerInfoLoopAgain,
    ], () => {
        RES.successResponse(res, resultData);
    })


}